using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using DocumentCreationSystem.Models;
using Microsoft.Extensions.Logging;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// 增强的意图识别器
    /// </summary>
    public partial class EnhancedIntentRecognizer
    {
        private readonly ILogger<EnhancedIntentRecognizer> _logger;
        private readonly IAIService _aiService;

        // 意图模式库
        private readonly Dictionary<IntentType, List<string>> _intentPatterns = new()
        {
            [IntentType.FileOperation] = new()
            {
                @"(创建|新建|生成|写入).*文件",
                @"(读取|查看|打开|显示).*文件",
                @"(删除|移除|清除).*文件",
                @"(移动|复制|重命名).*文件",
                @"(修改|编辑|更新).*文件"
            },
            [IntentType.ContentAnalysis] = new()
            {
                @"(分析|解析|检查|评估).*内容",
                @"(总结|摘要|概括).*",
                @"(比较|对比).*",
                @"(统计|计算|统计).*",
                @"(提取|获取).*信息"
            },
            [IntentType.ContentGeneration] = new()
            {
                @"(生成|创作|写作|编写).*",
                @"(续写|补充|扩展).*",
                @"(改写|重写|优化).*",
                @"(翻译|转换).*",
                @"(创建|制作).*大纲"
            },
            [IntentType.ProjectManagement] = new()
            {
                @"(管理|组织|整理).*项目",
                @"(扫描|检查|分析).*项目",
                @"(备份|同步|导出).*项目",
                @"(搜索|查找|定位).*项目",
                @"(配置|设置|调整).*项目"
            },
            [IntentType.QualityControl] = new()
            {
                @"(检查|验证|审核).*质量",
                @"(校对|纠错|修正).*",
                @"(优化|改进|提升).*",
                @"(评分|评估|打分).*",
                @"(一致性|连贯性).*检查"
            },
            [IntentType.Collaboration] = new()
            {
                @"(协作|合作|配合).*",
                @"(分享|共享|发布).*",
                @"(讨论|商议|咨询).*",
                @"(反馈|建议|意见).*",
                @"(团队|多人).*工作"
            },
            // 新增：人物角色规划意图
            [IntentType.CharacterPlanning] = new()
            {
                @"(设计|创建|规划|构思).*角色",
                @"(设计|创建|规划|构思).*人物",
                @"(角色|人物).*(设定|属性|特征)",
                @"(角色|人物).*(关系|网络|互动)",
                @"(角色|人物).*(发展|成长|变化)",
                @"(主角|配角|反派|龙套).*(设计|规划)",
                @"(人物|角色).*(性格|背景|经历)",
                @"(建立|构建).*(角色|人物).*体系",
                @"(分析|梳理).*(角色|人物).*关系",
                @"(规划|安排).*(角色|人物).*出场"
            },
            // 新增：工作流规划意图
            [IntentType.WorkflowPlanning] = new()
            {
                @"(规划|制定|设计).*流程",
                @"(规划|制定|设计).*步骤",
                @"(规划|制定|设计).*计划",
                @"(安排|组织|编排).*任务",
                @"(安排|组织|编排).*工作",
                @"(流程|步骤|计划).*(优化|改进)",
                @"(自动化|批量).*(处理|执行)",
                @"(顺序|并行).*(执行|处理)",
                @"(任务|工作).*(分解|拆分)",
                @"(执行|运行).*(计划|流程)",
                @"(监控|跟踪).*(进度|状态)",
                @"(一键|自动).*(生成|创建|执行)"
            }
        };

        public EnhancedIntentRecognizer(ILogger<EnhancedIntentRecognizer> logger, IAIService aiService)
        {
            _logger = logger;
            _aiService = aiService;
        }

        /// <summary>
        /// 分析用户意图
        /// </summary>
        public async Task<ComplexIntent> AnalyzeUserIntentAsync(string userInput)
        {
            try
            {
                _logger.LogInformation($"开始分析用户意图: {userInput}");

                var intent = new ComplexIntent
                {
                    OriginalInput = userInput,
                    AnalyzedAt = DateTime.Now
                };

                // 1. 基础意图识别
                intent.PrimaryIntent = IdentifyPrimaryIntent(userInput);
                intent.SecondaryIntents = IdentifySecondaryIntents(userInput);

                // 2. 实体提取
                intent.Entities = ExtractEntities(userInput);

                // 3. 上下文分析
                intent.Context = await AnalyzeContextAsync(userInput);

                // 4. 专门的规划意图分析
                await AnalyzeSpecializedPlanningIntentsAsync(intent, userInput);

                // 5. 复杂度评估
                intent.Complexity = EvaluateComplexity(intent);

                // 6. 置信度计算
                intent.Confidence = CalculateConfidence(intent);

                // 7. 参数提取
                intent.Parameters = ExtractParameters(userInput, intent);

                _logger.LogInformation($"意图分析完成，主要意图: {intent.PrimaryIntent.Type}，置信度: {intent.Confidence:F2}");
                return intent;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "分析用户意图时发生错误");
                throw;
            }
        }

        /// <summary>
        /// 分解复杂任务
        /// </summary>
        public async Task<TaskDecomposition> DecomposeComplexTaskAsync(ComplexIntent intent)
        {
            try
            {
                _logger.LogInformation($"开始分解复杂任务，意图类型: {intent.PrimaryIntent.Type}");

                var decomposition = new TaskDecomposition
                {
                    OriginalIntent = intent,
                    DecomposedAt = DateTime.Now
                };

                // 1. 任务分解策略选择
                var strategy = SelectDecompositionStrategy(intent);
                decomposition.Strategy = strategy;

                // 2. 子任务识别
                decomposition.SubTasks = await IdentifySubTasksAsync(intent, strategy);

                // 3. 依赖关系分析
                AnalyzeDependencies(decomposition.SubTasks);

                // 4. 优先级排序
                PrioritizeSubTasks(decomposition.SubTasks);

                // 5. 资源需求评估
                decomposition.ResourceRequirements = EvaluateResourceRequirements(decomposition.SubTasks);

                _logger.LogInformation($"任务分解完成，生成 {decomposition.SubTasks.Count} 个子任务");
                return decomposition;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "分解复杂任务时发生错误");
                throw;
            }
        }

        /// <summary>
        /// 生成执行计划
        /// </summary>
        public async Task<ExecutionPlan> GenerateExecutionPlanAsync(TaskDecomposition decomposition)
        {
            try
            {
                _logger.LogInformation("开始生成执行计划");

                var plan = new ExecutionPlan
                {
                    TaskDecomposition = decomposition,
                    CreatedAt = DateTime.Now
                };

                // 1. 执行顺序优化
                plan.ExecutionOrder = OptimizeExecutionOrder(decomposition.SubTasks);

                // 2. 并行执行分组
                plan.ParallelGroups = GroupParallelTasks(plan.ExecutionOrder);

                // 3. 检查点设置
                plan.Checkpoints = SetupCheckpoints(plan.ExecutionOrder);

                // 4. 错误处理策略
                plan.ErrorHandlingStrategy = DefineErrorHandlingStrategy(decomposition);

                // 5. 预估执行时间
                plan.EstimatedDuration = CalculateEstimatedDuration(plan.ExecutionOrder);

                // 6. 成功标准定义
                plan.SuccessCriteria = DefineSuccessCriteria(decomposition.OriginalIntent);

                _logger.LogInformation($"执行计划生成完成，预估耗时: {plan.EstimatedDuration}");
                return plan;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成执行计划时发生错误");
                throw;
            }
        }

        #region 私有方法

        private IntentInfo IdentifyPrimaryIntent(string input)
        {
            var intent = new IntentInfo();
            double maxScore = 0;

            foreach (var intentType in _intentPatterns.Keys)
            {
                var score = CalculateIntentScore(input, intentType);
                if (score > maxScore)
                {
                    maxScore = score;
                    intent.Type = intentType;
                    intent.Confidence = score;
                }
            }

            intent.Description = GenerateIntentDescription(intent.Type, input);
            return intent;
        }

        private List<IntentInfo> IdentifySecondaryIntents(string input)
        {
            var secondaryIntents = new List<IntentInfo>();

            foreach (var intentType in _intentPatterns.Keys)
            {
                var score = CalculateIntentScore(input, intentType);
                if (score > 0.3 && score < 0.8) // 中等置信度的意图作为次要意图
                {
                    secondaryIntents.Add(new IntentInfo
                    {
                        Type = intentType,
                        Confidence = score,
                        Description = GenerateIntentDescription(intentType, input)
                    });
                }
            }

            return secondaryIntents.OrderByDescending(i => i.Confidence).Take(3).ToList();
        }

        private double CalculateIntentScore(string input, IntentType intentType)
        {
            var patterns = _intentPatterns[intentType];
            double totalScore = 0;

            foreach (var pattern in patterns)
            {
                if (Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase))
                {
                    totalScore += 1.0 / patterns.Count;
                }
            }

            return Math.Min(totalScore, 1.0);
        }

        private List<EntityInfo> ExtractEntities(string input)
        {
            var entities = new List<EntityInfo>();

            // 文件路径提取
            var filePathPattern = @"[a-zA-Z]:\\[^<>:""|?*\s]+|\.\/[^<>:""|?*\s]+|[^<>:""|?*\s]+\.[a-zA-Z0-9]+";
            var fileMatches = Regex.Matches(input, filePathPattern);
            foreach (Match match in fileMatches)
            {
                entities.Add(new EntityInfo
                {
                    Type = EntityType.FilePath,
                    Value = match.Value,
                    Position = match.Index,
                    Confidence = 0.8
                });
            }

            // 数字提取
            var numberPattern = @"\b\d+\b";
            var numberMatches = Regex.Matches(input, numberPattern);
            foreach (Match match in numberMatches)
            {
                entities.Add(new EntityInfo
                {
                    Type = EntityType.Number,
                    Value = match.Value,
                    Position = match.Index,
                    Confidence = 0.9
                });
            }

            // 关键词提取
            var keywords = ExtractKeywords(input);
            foreach (var keyword in keywords)
            {
                entities.Add(new EntityInfo
                {
                    Type = EntityType.Keyword,
                    Value = keyword,
                    Position = input.IndexOf(keyword),
                    Confidence = 0.7
                });
            }

            return entities;
        }

        private List<string> ExtractKeywords(string input)
        {
            // 简单的关键词提取逻辑
            var words = input.Split(new char[] { ' ', '\t', '\n', '\r', ',', '.', '!', '?' }, 
                StringSplitOptions.RemoveEmptyEntries);
            
            var stopWords = new HashSet<string> { "的", "是", "在", "有", "和", "与", "或", "但", "然而", "因为", "所以" };
            
            return words.Where(w => w.Length > 2 && !stopWords.Contains(w))
                       .GroupBy(w => w.ToLower())
                       .Where(g => g.Count() >= 1)
                       .Select(g => g.Key)
                       .Take(10)
                       .ToList();
        }

        private async Task<ContextInfo> AnalyzeContextAsync(string input)
        {
            var context = new ContextInfo();
            
            // 时间上下文
            if (Regex.IsMatch(input, @"(现在|立即|马上|今天|明天|昨天)"))
            {
                context.Temporal = "Immediate";
            }
            else if (Regex.IsMatch(input, @"(稍后|以后|将来|下次)"))
            {
                context.Temporal = "Future";
            }

            // 紧急程度
            if (Regex.IsMatch(input, @"(紧急|急|快|立即|马上)"))
            {
                context.Urgency = UrgencyLevel.High;
            }
            else if (Regex.IsMatch(input, @"(慢慢|仔细|详细|认真)"))
            {
                context.Urgency = UrgencyLevel.Low;
            }
            else
            {
                context.Urgency = UrgencyLevel.Medium;
            }

            return context;
        }

        private ComplexityLevel EvaluateComplexity(ComplexIntent intent)
        {
            var score = 0;

            // 基于意图类型评分
            score += intent.PrimaryIntent.Type switch
            {
                IntentType.FileOperation => 1,
                IntentType.ContentAnalysis => 2,
                IntentType.ContentGeneration => 3,
                IntentType.ProjectManagement => 3,
                IntentType.QualityControl => 4,
                IntentType.Collaboration => 4,
                _ => 1
            };

            // 基于实体数量评分
            score += intent.Entities.Count / 3;

            // 基于次要意图数量评分
            score += intent.SecondaryIntents.Count;

            return score switch
            {
                <= 2 => ComplexityLevel.Simple,
                <= 4 => ComplexityLevel.Medium,
                <= 6 => ComplexityLevel.Complex,
                _ => ComplexityLevel.VeryComplex
            };
        }

        private double CalculateConfidence(ComplexIntent intent)
        {
            var confidence = intent.PrimaryIntent.Confidence;
            
            // 基于实体提取质量调整
            if (intent.Entities.Any())
            {
                confidence += intent.Entities.Average(e => e.Confidence) * 0.2;
            }

            // 基于上下文清晰度调整
            if (intent.Context.Urgency != UrgencyLevel.Unknown)
            {
                confidence += 0.1;
            }

            return Math.Min(confidence, 1.0);
        }

        private Dictionary<string, object> ExtractParameters(string input, ComplexIntent intent)
        {
            var parameters = new Dictionary<string, object>();

            // 从实体中提取参数
            foreach (var entity in intent.Entities)
            {
                switch (entity.Type)
                {
                    case EntityType.FilePath:
                        parameters["filePath"] = entity.Value;
                        break;
                    case EntityType.Number:
                        parameters["number"] = int.Parse(entity.Value);
                        break;
                    case EntityType.Keyword:
                        if (!parameters.ContainsKey("keywords"))
                            parameters["keywords"] = new List<string>();
                        ((List<string>)parameters["keywords"]).Add(entity.Value);
                        break;
                }
            }

            return parameters;
        }

        private string GenerateIntentDescription(IntentType type, string input)
        {
            return type switch
            {
                IntentType.FileOperation => "用户想要进行文件操作",
                IntentType.ContentAnalysis => "用户想要分析内容",
                IntentType.ContentGeneration => "用户想要生成内容",
                IntentType.ProjectManagement => "用户想要管理项目",
                IntentType.QualityControl => "用户想要进行质量控制",
                IntentType.Collaboration => "用户想要进行协作",
                _ => "未知意图"
            };
        }

        private DecompositionStrategy SelectDecompositionStrategy(ComplexIntent intent)
        {
            return new DecompositionStrategy
            {
                Name = intent.Complexity switch
                {
                    ComplexityLevel.Simple => "简单顺序策略",
                    ComplexityLevel.Medium => "平衡策略",
                    ComplexityLevel.Complex => "分层策略",
                    ComplexityLevel.VeryComplex => "自适应策略",
                    _ => "默认策略"
                },
                Type = intent.Complexity switch
                {
                    ComplexityLevel.Simple => StrategyType.Sequential,
                    ComplexityLevel.Medium => StrategyType.Parallel,
                    ComplexityLevel.Complex => StrategyType.Hierarchical,
                    ComplexityLevel.VeryComplex => StrategyType.Adaptive,
                    _ => StrategyType.Sequential
                }
            };
        }

        private async Task<List<SubTask>> IdentifySubTasksAsync(ComplexIntent intent, DecompositionStrategy strategy)
        {
            var subTasks = new List<SubTask>();

            switch (intent.PrimaryIntent.Type)
            {
                case IntentType.FileOperation:
                    subTasks.AddRange(CreateFileOperationTasks(intent));
                    break;
                case IntentType.ContentGeneration:
                    subTasks.AddRange(CreateContentGenerationTasks(intent));
                    break;
                case IntentType.ContentAnalysis:
                    subTasks.AddRange(CreateContentAnalysisTasks(intent));
                    break;
                case IntentType.ProjectManagement:
                    subTasks.AddRange(CreateProjectManagementTasks(intent));
                    break;
                default:
                    subTasks.Add(CreateGenericTask(intent));
                    break;
            }

            return subTasks;
        }

        private List<SubTask> CreateFileOperationTasks(ComplexIntent intent)
        {
            return new List<SubTask>
            {
                new SubTask
                {
                    Name = "文件路径验证",
                    Description = "验证文件路径的有效性",
                    Type = TaskType.Analysis,
                    Priority = TaskPriority.High,
                    EstimatedMinutes = 1
                },
                new SubTask
                {
                    Name = "执行文件操作",
                    Description = "执行具体的文件操作",
                    Type = TaskType.Integration,
                    Priority = TaskPriority.Medium,
                    EstimatedMinutes = 1
                }
            };
        }

        private List<SubTask> CreateContentGenerationTasks(ComplexIntent intent)
        {
            return new List<SubTask>
            {
                new SubTask
                {
                    Name = "内容规划",
                    Description = "制定内容生成计划",
                    Type = TaskType.Planning,
                    Priority = TaskPriority.High,
                    EstimatedMinutes = 2
                },
                new SubTask
                {
                    Name = "内容生成",
                    Description = "生成具体内容",
                    Type = TaskType.Creation,
                    Priority = TaskPriority.High,
                    EstimatedMinutes = 5
                },
                new SubTask
                {
                    Name = "质量检查",
                    Description = "检查生成内容的质量",
                    Type = TaskType.Review,
                    Priority = TaskPriority.Medium,
                    EstimatedMinutes = 1
                }
            };
        }

        private List<SubTask> CreateContentAnalysisTasks(ComplexIntent intent)
        {
            return new List<SubTask>
            {
                new SubTask
                {
                    Name = "内容读取",
                    Description = "读取待分析的内容",
                    Type = TaskType.Analysis,
                    Priority = TaskPriority.High,
                    EstimatedMinutes = 1
                },
                new SubTask
                {
                    Name = "内容分析",
                    Description = "分析内容特征和结构",
                    Type = TaskType.Analysis,
                    Priority = TaskPriority.High,
                    EstimatedMinutes = 3
                },
                new SubTask
                {
                    Name = "结果整理",
                    Description = "整理分析结果",
                    Type = TaskType.Integration,
                    Priority = TaskPriority.Medium,
                    EstimatedMinutes = 1
                }
            };
        }

        private List<SubTask> CreateProjectManagementTasks(ComplexIntent intent)
        {
            return new List<SubTask>
            {
                new SubTask
                {
                    Name = "项目扫描",
                    Description = "扫描项目结构和文件",
                    Type = TaskType.Analysis,
                    Priority = TaskPriority.High,
                    EstimatedMinutes = 1
                },
                new SubTask
                {
                    Name = "项目分析",
                    Description = "分析项目特征和状态",
                    Type = TaskType.Analysis,
                    Priority = TaskPriority.Medium,
                    EstimatedMinutes = 2
                }
            };
        }

        private SubTask CreateGenericTask(ComplexIntent intent)
        {
            return new SubTask
            {
                Name = "通用任务处理",
                Description = "处理通用类型的任务",
                Type = TaskType.Integration,
                Priority = TaskPriority.Medium,
                EstimatedMinutes = 2
            };
        }

        private void AnalyzeDependencies(List<SubTask> subTasks)
        {
            // 注意：Models.SubTask没有Dependencies属性，这里需要其他方式处理依赖关系
            // 暂时跳过依赖关系设置
        }

        private void PrioritizeSubTasks(List<SubTask> subTasks)
        {
            for (int i = 0; i < subTasks.Count; i++)
            {
                subTasks[i].Priority = i == 0 ? TaskPriority.High :
                                     i == 1 ? TaskPriority.Medium : TaskPriority.Low;
            }
        }

        private ResourceRequirements EvaluateResourceRequirements(List<SubTask> subTasks)
        {
            return new ResourceRequirements
            {
                CpuRequirement = ResourceLevel.Medium,
                MemoryRequirement = ResourceLevel.Medium,
                ModelCallsEstimate = subTasks.Count(t => t.Type == TaskType.Creation || t.Type == TaskType.Analysis) * 2,
                RequiresNetwork = false, // Models.SubTask没有RequiredSkills属性
                StorageRequirement = 1024 * 1024 // 1MB
            };
        }

        private List<string> OptimizeExecutionOrder(List<SubTask> subTasks)
        {
            return subTasks.OrderBy(t => (int)t.Priority).Select(t => t.Id).ToList();
        }

        private List<ParallelGroup> GroupParallelTasks(List<string> executionOrder)
        {
            var groups = new List<ParallelGroup>();

            // 简单的分组策略：每3个任务一组
            for (int i = 0; i < executionOrder.Count; i += 3)
            {
                var group = new ParallelGroup
                {
                    TaskIds = executionOrder.Skip(i).Take(3).ToList(),
                    MaxConcurrency = 2
                };
                groups.Add(group);
            }

            return groups;
        }

        private List<ExecutionCheckpoint> SetupCheckpoints(List<string> executionOrder)
        {
            var checkpoints = new List<ExecutionCheckpoint>();

            // 在中间和结尾设置检查点
            if (executionOrder.Count > 2)
            {
                checkpoints.Add(new ExecutionCheckpoint
                {
                    Name = "中期检查",
                    TriggerCondition = $"完成任务数量 >= {executionOrder.Count / 2}",
                    Criteria = new List<string> { "质量检查", "进度检查" }
                });
            }

            checkpoints.Add(new ExecutionCheckpoint
            {
                Name = "最终检查",
                TriggerCondition = "所有任务完成",
                Criteria = new List<string> { "完整性检查", "质量验收" }
            });

            return checkpoints;
        }

        private ErrorHandlingStrategy DefineErrorHandlingStrategy(TaskDecomposition decomposition)
        {
            return new ErrorHandlingStrategy
            {
                RetryPolicy = new RetryPolicy
                {
                    MaxRetries = 3,
                    RetryInterval = TimeSpan.FromSeconds(5),
                    UseExponentialBackoff = true
                },
                RollbackPolicy = new RollbackPolicy
                {
                    EnableAutoRollback = true,
                    TriggerConditions = new List<string> { "严重错误", "资源不足" }
                },
                NotificationPolicy = new NotificationPolicy
                {
                    Level = NotificationLevel.Error,
                    Methods = new List<string> { "日志", "界面提示" }
                }
            };
        }

        private TimeSpan CalculateEstimatedDuration(List<string> executionOrder)
        {
            // 简化计算：假设每个任务平均2分钟
            return TimeSpan.FromMinutes(executionOrder.Count * 2);
        }

        private List<string> DefineSuccessCriteria(ComplexIntent intent)
        {
            return new List<string>
            {
                "所有子任务成功完成",
                "输出质量达到要求",
                "用户满意度达标"
            };
        }

        #endregion
    }

    /// <summary>
    /// 复杂意图
    /// </summary>
    public class ComplexIntent
    {
        /// <summary>
        /// 原始输入
        /// </summary>
        public string OriginalInput { get; set; } = string.Empty;

        /// <summary>
        /// 主要意图
        /// </summary>
        public IntentInfo PrimaryIntent { get; set; } = new();

        /// <summary>
        /// 次要意图列表
        /// </summary>
        public List<IntentInfo> SecondaryIntents { get; set; } = new();

        /// <summary>
        /// 提取的实体
        /// </summary>
        public List<EntityInfo> Entities { get; set; } = new();

        /// <summary>
        /// 上下文信息
        /// </summary>
        public ContextInfo Context { get; set; } = new();

        /// <summary>
        /// 复杂度等级
        /// </summary>
        public ComplexityLevel Complexity { get; set; }

        /// <summary>
        /// 总体置信度
        /// </summary>
        public double Confidence { get; set; }

        /// <summary>
        /// 提取的参数
        /// </summary>
        public Dictionary<string, object> Parameters { get; set; } = new();

        /// <summary>
        /// 专门的意图分析结果
        /// </summary>
        public Dictionary<string, object> SpecializedIntents { get; set; } = new();

        /// <summary>
        /// 分析时间
        /// </summary>
        public DateTime AnalyzedAt { get; set; }

        /// <summary>
        /// 所需能力列表
        /// </summary>
        public List<string> RequiredCapabilities { get; set; } = new();

        /// <summary>
        /// 用户输入（别名，兼容性）
        /// </summary>
        public string UserInput => OriginalInput;

        /// <summary>
        /// 意图类型（别名，兼容性）
        /// </summary>
        public IntentType IntentType => PrimaryIntent.Type;
    }

    /// <summary>
    /// 意图信息
    /// </summary>
    public class IntentInfo
    {
        /// <summary>
        /// 意图类型
        /// </summary>
        public IntentType Type { get; set; }

        /// <summary>
        /// 置信度
        /// </summary>
        public double Confidence { get; set; }

        /// <summary>
        /// 描述
        /// </summary>
        public string Description { get; set; } = string.Empty;

        /// <summary>
        /// 相关关键词
        /// </summary>
        public List<string> Keywords { get; set; } = new();
    }

    /// <summary>
    /// 意图类型
    /// </summary>
    public enum IntentType
    {
        FileOperation,
        ContentAnalysis,
        ContentGeneration,
        ProjectManagement,
        QualityControl,
        Collaboration,
        CharacterPlanning,
        WorkflowPlanning,
        Unknown
    }

    /// <summary>
    /// 实体信息
    /// </summary>
    public class EntityInfo
    {
        /// <summary>
        /// 实体类型
        /// </summary>
        public EntityType Type { get; set; }

        /// <summary>
        /// 实体值
        /// </summary>
        public string Value { get; set; } = string.Empty;

        /// <summary>
        /// 在原文中的位置
        /// </summary>
        public int Position { get; set; }

        /// <summary>
        /// 置信度
        /// </summary>
        public double Confidence { get; set; }

        /// <summary>
        /// 附加属性
        /// </summary>
        public Dictionary<string, object> Attributes { get; set; } = new();
    }

    /// <summary>
    /// 实体类型
    /// </summary>
    public enum EntityType
    {
        FilePath,
        Number,
        Keyword,
        Date,
        Time,
        Person,
        Organization,
        Location,
        Technology
    }

    /// <summary>
    /// 上下文信息
    /// </summary>
    public class ContextInfo
    {
        /// <summary>
        /// 时间上下文
        /// </summary>
        public string Temporal { get; set; } = string.Empty;

        /// <summary>
        /// 紧急程度
        /// </summary>
        public UrgencyLevel Urgency { get; set; } = UrgencyLevel.Unknown;

        /// <summary>
        /// 工作模式
        /// </summary>
        public WorkMode Mode { get; set; } = WorkMode.Unknown;

        /// <summary>
        /// 质量要求
        /// </summary>
        public QualityRequirement Quality { get; set; } = QualityRequirement.Unknown;

        /// <summary>
        /// 环境信息
        /// </summary>
        public Dictionary<string, object> Environment { get; set; } = new();
    }

    /// <summary>
    /// 紧急程度
    /// </summary>
    public enum UrgencyLevel
    {
        Unknown,
        Low,
        Medium,
        High,
        Critical
    }

    /// <summary>
    /// 工作模式
    /// </summary>
    public enum WorkMode
    {
        Unknown,
        Interactive,
        Batch,
        Automated,
        Collaborative
    }

    /// <summary>
    /// 质量要求
    /// </summary>
    public enum QualityRequirement
    {
        Unknown,
        Draft,
        Standard,
        High,
        Professional
    }

    /// <summary>
    /// 复杂度等级
    /// </summary>
    public enum ComplexityLevel
    {
        Simple,
        Medium,
        Complex,
        VeryComplex
    }

    /// <summary>
    /// 任务分解
    /// </summary>
    public class TaskDecomposition
    {
        /// <summary>
        /// 原始意图
        /// </summary>
        public ComplexIntent OriginalIntent { get; set; } = new();

        /// <summary>
        /// 分解策略
        /// </summary>
        public DecompositionStrategy Strategy { get; set; } = new();

        /// <summary>
        /// 子任务列表
        /// </summary>
        public List<SubTask> SubTasks { get; set; } = new();

        /// <summary>
        /// 资源需求
        /// </summary>
        public ResourceRequirements ResourceRequirements { get; set; } = new();

        /// <summary>
        /// 分解时间
        /// </summary>
        public DateTime DecomposedAt { get; set; }
    }

    /// <summary>
    /// 分解策略
    /// </summary>
    public class DecompositionStrategy
    {
        /// <summary>
        /// 策略名称
        /// </summary>
        public string Name { get; set; } = string.Empty;

        /// <summary>
        /// 策略类型
        /// </summary>
        public StrategyType Type { get; set; }

        /// <summary>
        /// 参数配置
        /// </summary>
        public Dictionary<string, object> Parameters { get; set; } = new();
    }

    /// <summary>
    /// 策略类型
    /// </summary>
    public enum StrategyType
    {
        Sequential,
        Parallel,
        Hierarchical,
        Adaptive
    }



    /// <summary>
    /// 资源需求
    /// </summary>
    public class ResourceRequirements
    {
        /// <summary>
        /// CPU需求
        /// </summary>
        public ResourceLevel CpuRequirement { get; set; }

        /// <summary>
        /// 内存需求
        /// </summary>
        public ResourceLevel MemoryRequirement { get; set; }

        /// <summary>
        /// AI模型调用次数
        /// </summary>
        public int ModelCallsEstimate { get; set; }

        /// <summary>
        /// 网络需求
        /// </summary>
        public bool RequiresNetwork { get; set; }

        /// <summary>
        /// 存储需求
        /// </summary>
        public long StorageRequirement { get; set; }

        /// <summary>
        /// 特殊资源
        /// </summary>
        public List<string> SpecialResources { get; set; } = new();
    }

    /// <summary>
    /// 资源等级
    /// </summary>
    public enum ResourceLevel
    {
        Low,
        Medium,
        High,
        VeryHigh
    }

    /// <summary>
    /// 执行计划
    /// </summary>
    public class ExecutionPlan
    {
        /// <summary>
        /// 计划ID
        /// </summary>
        public string Id { get; set; } = Guid.NewGuid().ToString();

        /// <summary>
        /// 任务分解
        /// </summary>
        public TaskDecomposition TaskDecomposition { get; set; } = new();

        /// <summary>
        /// 执行顺序
        /// </summary>
        public List<string> ExecutionOrder { get; set; } = new();

        /// <summary>
        /// 并行执行组
        /// </summary>
        public List<ParallelGroup> ParallelGroups { get; set; } = new();

        /// <summary>
        /// 检查点
        /// </summary>
        public List<ExecutionCheckpoint> Checkpoints { get; set; } = new();

        /// <summary>
        /// 错误处理策略
        /// </summary>
        public ErrorHandlingStrategy ErrorHandlingStrategy { get; set; } = new();

        /// <summary>
        /// 预估执行时间
        /// </summary>
        public TimeSpan EstimatedDuration { get; set; }

        /// <summary>
        /// 成功标准
        /// </summary>
        public List<string> SuccessCriteria { get; set; } = new();

        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime CreatedAt { get; set; }
    }

    /// <summary>
    /// 并行执行组
    /// </summary>
    public class ParallelGroup
    {
        /// <summary>
        /// 组ID
        /// </summary>
        public string Id { get; set; } = Guid.NewGuid().ToString();

        /// <summary>
        /// 组内任务
        /// </summary>
        public List<string> TaskIds { get; set; } = new();

        /// <summary>
        /// 最大并发数
        /// </summary>
        public int MaxConcurrency { get; set; } = 3;

        /// <summary>
        /// 同步点
        /// </summary>
        public bool RequiresSynchronization { get; set; } = true;
    }

    /// <summary>
    /// 执行检查点
    /// </summary>
    public class ExecutionCheckpoint
    {
        /// <summary>
        /// 检查点名称
        /// </summary>
        public string Name { get; set; } = string.Empty;

        /// <summary>
        /// 触发条件
        /// </summary>
        public string TriggerCondition { get; set; } = string.Empty;

        /// <summary>
        /// 检查标准
        /// </summary>
        public List<string> Criteria { get; set; } = new();

        /// <summary>
        /// 失败时的操作
        /// </summary>
        public string FailureAction { get; set; } = string.Empty;
    }

    /// <summary>
    /// 错误处理策略
    /// </summary>
    public class ErrorHandlingStrategy
    {
        /// <summary>
        /// 重试策略
        /// </summary>
        public RetryPolicy RetryPolicy { get; set; } = new();

        /// <summary>
        /// 回滚策略
        /// </summary>
        public RollbackPolicy RollbackPolicy { get; set; } = new();

        /// <summary>
        /// 通知策略
        /// </summary>
        public NotificationPolicy NotificationPolicy { get; set; } = new();
    }

    /// <summary>
    /// 重试策略
    /// </summary>
    public class RetryPolicy
    {
        /// <summary>
        /// 最大重试次数
        /// </summary>
        public int MaxRetries { get; set; } = 3;

        /// <summary>
        /// 重试间隔
        /// </summary>
        public TimeSpan RetryInterval { get; set; } = TimeSpan.FromSeconds(5);

        /// <summary>
        /// 指数退避
        /// </summary>
        public bool UseExponentialBackoff { get; set; } = true;
    }

    /// <summary>
    /// 回滚策略
    /// </summary>
    public class RollbackPolicy
    {
        /// <summary>
        /// 是否启用自动回滚
        /// </summary>
        public bool EnableAutoRollback { get; set; } = true;

        /// <summary>
        /// 回滚触发条件
        /// </summary>
        public List<string> TriggerConditions { get; set; } = new();
    }

    /// <summary>
    /// 通知策略
    /// </summary>
    public class NotificationPolicy
    {
        /// <summary>
        /// 通知级别
        /// </summary>
        public NotificationLevel Level { get; set; } = NotificationLevel.Error;

        /// <summary>
        /// 通知方式
        /// </summary>
        public List<string> Methods { get; set; } = new();
    }

    /// <summary>
    /// 通知级别
    /// </summary>
    public enum NotificationLevel
    {
        Info,
        Warning,
        Error,
        Critical
    }

    // 扩展方法：专门的规划意图分析
    public partial class EnhancedIntentRecognizer
    {
        /// <summary>
        /// 分析专门的规划意图（人物规划和工作流规划）
        /// </summary>
        private async Task AnalyzeSpecializedPlanningIntentsAsync(ComplexIntent intent, string userInput)
        {
            // 分析人物角色规划意图
            var characterPlanningIntent = await AnalyzeCharacterPlanningIntentAsync(userInput);
            if (characterPlanningIntent != null)
            {
                intent.SpecializedIntents.Add("CharacterPlanning", characterPlanningIntent);
            }

            // 分析工作流规划意图
            var workflowPlanningIntent = await AnalyzeWorkflowPlanningIntentAsync(userInput);
            if (workflowPlanningIntent != null)
            {
                intent.SpecializedIntents.Add("WorkflowPlanning", workflowPlanningIntent);
            }
        }

        /// <summary>
        /// 分析人物角色规划意图
        /// </summary>
        private async Task<CharacterPlanningIntent?> AnalyzeCharacterPlanningIntentAsync(string userInput)
        {
            var characterKeywords = new[]
            {
                "角色", "人物", "主角", "配角", "反派", "龙套",
                "性格", "背景", "经历", "关系", "发展", "成长",
                "设定", "属性", "特征", "互动", "网络"
            };

            if (!characterKeywords.Any(k => userInput.Contains(k, StringComparison.OrdinalIgnoreCase)))
                return null;

            var intent = new CharacterPlanningIntent
            {
                DetectedAt = DateTime.Now,
                Confidence = CalculateKeywordConfidence(userInput, characterKeywords)
            };

            // 分析具体的角色规划类型
            intent.PlanningType = DetermineCharacterPlanningType(userInput);
            intent.TargetCharacters = ExtractCharacterReferences(userInput);
            intent.PlanningScope = DetermineCharacterPlanningScope(userInput);
            intent.RequiredAttributes = ExtractRequiredCharacterAttributes(userInput);

            return intent;
        }

        /// <summary>
        /// 分析工作流规划意图
        /// </summary>
        private async Task<WorkflowPlanningIntent?> AnalyzeWorkflowPlanningIntentAsync(string userInput)
        {
            var workflowKeywords = new[]
            {
                "流程", "步骤", "计划", "任务", "工作", "执行",
                "安排", "组织", "编排", "自动化", "批量",
                "顺序", "并行", "分解", "拆分", "监控", "跟踪"
            };

            if (!workflowKeywords.Any(k => userInput.Contains(k, StringComparison.OrdinalIgnoreCase)))
                return null;

            var intent = new WorkflowPlanningIntent
            {
                DetectedAt = DateTime.Now,
                Confidence = CalculateKeywordConfidence(userInput, workflowKeywords)
            };

            // 分析具体的工作流规划类型
            intent.PlanningType = DetermineWorkflowPlanningType(userInput);
            intent.ExecutionMode = DetermineExecutionMode(userInput);
            intent.TargetScope = DetermineWorkflowScope(userInput);
            intent.RequiredSteps = ExtractRequiredSteps(userInput);

            return intent;
        }

        /// <summary>
        /// 确定角色规划类型
        /// </summary>
        private CharacterPlanningType DetermineCharacterPlanningType(string userInput)
        {
            if (userInput.Contains("创建") || userInput.Contains("设计") || userInput.Contains("新建"))
                return CharacterPlanningType.Creation;
            else if (userInput.Contains("关系") || userInput.Contains("网络") || userInput.Contains("互动"))
                return CharacterPlanningType.Relationship;
            else if (userInput.Contains("发展") || userInput.Contains("成长") || userInput.Contains("变化"))
                return CharacterPlanningType.Development;
            else if (userInput.Contains("分析") || userInput.Contains("梳理"))
                return CharacterPlanningType.Analysis;
            else
                return CharacterPlanningType.General;
        }

        /// <summary>
        /// 确定工作流规划类型
        /// </summary>
        private WorkflowPlanningType DetermineWorkflowPlanningType(string userInput)
        {
            if (userInput.Contains("自动化") || userInput.Contains("一键"))
                return WorkflowPlanningType.Automation;
            else if (userInput.Contains("批量") || userInput.Contains("大量"))
                return WorkflowPlanningType.Batch;
            else if (userInput.Contains("顺序") || userInput.Contains("步骤"))
                return WorkflowPlanningType.Sequential;
            else if (userInput.Contains("并行") || userInput.Contains("同时"))
                return WorkflowPlanningType.Parallel;
            else if (userInput.Contains("监控") || userInput.Contains("跟踪"))
                return WorkflowPlanningType.Monitoring;
            else
                return WorkflowPlanningType.General;
        }

        /// <summary>
        /// 确定执行模式
        /// </summary>
        private WorkflowExecutionMode DetermineExecutionMode(string userInput)
        {
            if (userInput.Contains("并行") || userInput.Contains("同时"))
                return WorkflowExecutionMode.Parallel;
            else if (userInput.Contains("自适应") || userInput.Contains("智能"))
                return WorkflowExecutionMode.Adaptive;
            else
                return WorkflowExecutionMode.Sequential;
        }

        /// <summary>
        /// 计算关键词置信度
        /// </summary>
        private double CalculateKeywordConfidence(string userInput, string[] keywords)
        {
            var matchCount = keywords.Count(k => userInput.Contains(k, StringComparison.OrdinalIgnoreCase));
            return Math.Min(1.0, (double)matchCount / keywords.Length * 2);
        }

        /// <summary>
        /// 提取角色引用
        /// </summary>
        private List<string> ExtractCharacterReferences(string userInput)
        {
            var references = new List<string>();
            var patterns = new[]
            {
                @"角色""([^""]+)""",
                @"人物""([^""]+)""",
                @"主角""([^""]+)""",
                @"配角""([^""]+)"""
            };

            foreach (var pattern in patterns)
            {
                var matches = Regex.Matches(userInput, pattern);
                references.AddRange(matches.Cast<Match>().Select(m => m.Groups[1].Value));
            }

            return references.Distinct().ToList();
        }

        /// <summary>
        /// 确定角色规划范围
        /// </summary>
        private CharacterPlanningScope DetermineCharacterPlanningScope(string userInput)
        {
            if (userInput.Contains("所有") || userInput.Contains("全部"))
                return CharacterPlanningScope.All;
            else if (userInput.Contains("主要") || userInput.Contains("重要"))
                return CharacterPlanningScope.Major;
            else if (userInput.Contains("单个") || userInput.Contains("特定"))
                return CharacterPlanningScope.Individual;
            else
                return CharacterPlanningScope.Relevant;
        }

        /// <summary>
        /// 提取所需角色属性
        /// </summary>
        private List<string> ExtractRequiredCharacterAttributes(string userInput)
        {
            var attributes = new List<string>();
            var attributeKeywords = new[]
            {
                "性格", "背景", "经历", "技能", "装备", "属性",
                "境界", "修为", "年龄", "外貌", "特征", "能力"
            };

            attributes.AddRange(attributeKeywords.Where(attr =>
                userInput.Contains(attr, StringComparison.OrdinalIgnoreCase)));

            return attributes;
        }

        /// <summary>
        /// 确定工作流范围
        /// </summary>
        private WorkflowPlanningScope DetermineWorkflowScope(string userInput)
        {
            if (userInput.Contains("项目") || userInput.Contains("整个"))
                return WorkflowPlanningScope.Project;
            else if (userInput.Contains("章节") || userInput.Contains("内容"))
                return WorkflowPlanningScope.Content;
            else if (userInput.Contains("任务") || userInput.Contains("单个"))
                return WorkflowPlanningScope.Task;
            else
                return WorkflowPlanningScope.Custom;
        }

        /// <summary>
        /// 提取所需步骤
        /// </summary>
        private List<string> ExtractRequiredSteps(string userInput)
        {
            var steps = new List<string>();
            var stepPatterns = new[]
            {
                @"第?(\d+)[步骤]",
                @"步骤(\d+)",
                @"([^，。；！？]+)步骤"
            };

            foreach (var pattern in stepPatterns)
            {
                var matches = Regex.Matches(userInput, pattern);
                steps.AddRange(matches.Cast<Match>().Select(m => m.Value));
            }

            return steps.Distinct().ToList();
        }
    }
}
